<template>
  <div>
    <el-row>
      <!-- 用户列表 -->
      <el-col :span="6" style="padding: 20px 20px 0px">
        <el-card>
          <div slot="header" class="clearfix">
            <span>在线用户</span>
          </div>
          <div v-if="showOnlineUsers">
            <template v-for="user in onlineUsers">
              <el-button
                v-if="user.userId !== id"
                :key="user.userId"
                style="
                  width: 100%;
                  margin: 0%;
                  font-size: 18px;
                  text-align: left;
                "
                @click="changeRoomTitle(user.username, 'user', user)"
              >
                {{ user.username }}
                <span v-if="roomTitle === user.username" style="color: #409eff">
                  <span style="font-size: 13px">(chatting)</span>
                </span>
                <span v-if="user.unreadMessages > 0" class="unread-badge">{{
                  user.unreadMessages
                }}</span>
              </el-button>
            </template>
          </div>
          <div v-else>
            <p>暂无用户信息</p>
          </div>
        </el-card>
      </el-col>

      <!-- 聊天框 -->
      <el-col :span="12" style="padding: 20px 0px 0px; height: 50%">
        <el-card class="box-card">
          <div
            slot="header"
            class="clearfix"
            style="display: flex; justify-content: center; align-items: center"
          >
            <i :class="roomIcon" style="margin-right: 5px; font-size: 24px"></i>
            <span>{{ roomTitle }}</span>
          </div>
          <div class="messages">
            <div
              v-for="(message, index) in filteredMessages"
              :key="index"
              :class="{
                'my-message': message.from === userID,
                'other-message': message.from !== userID,
              }"
            >
              <div class="message-bubble">{{ message.content }}</div>
            </div>
          </div>
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              placeholder="输入消息"
              @keyup.enter.native="sendMessage(roomTitle)"
              class="input-message"
            ></el-input>
            <el-button type="primary" @click="sendMessage(roomTitle)"
              >发送</el-button
            >
          </div>
        </el-card>
      </el-col>

      <!-- 聊天室列表 -->
      <el-col :span="6" style="padding: 20px 20px 0px">
        <el-card>
          <div slot="header" class="clearfix"></div>
          <!-- 创建群聊的模态框 -->
          <el-dialog :visible.sync="showCreateGroupModal" title="创建群聊">
            <el-form
              ref="createGroupForm"
              :model="createForm"
              label-width="80px"
            >
              <el-form-item label="群聊名称" prop="groupName">
                <el-input
                  v-model="createForm.groupName"
                  placeholder="请输入群聊名称"
                ></el-input>
              </el-form-item>
              <!-- 在这里添加其他群聊相关的表单项，如成员选择等 -->
            </el-form>
          </el-dialog>

          <!-- 聊天室列表 -->
          <div v-if="message.roomList.length > 0">
            <el-card v-for="room in message.roomList" :key="room.roomId">
              <div slot="header" class="clearfix">
                <span>{{ room.roomName }}</span>
                <el-button
                  type="text"
                  style="float: right; padding: 3px 0"
                  @click="enterRoom(room.roomName)"
                >
                  进入
                </el-button>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getInfo } from "../../../api/login";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      showCreateGroupModal: false, // 控制创建群聊模态框的显示
      createForm: {
        // 创建群聊表单数据
        groupName: "", // 群聊名称
        // 其他群聊相关的字段
      },
      userID: null,
      ws: null,
      isGroup: "0",
      messages: [],
      onlineUsers: [],
      inputMessage: "",
      roomTitle: "聊天室",
      roomIcon: "el-icon-s-comment",
      roomList: [],
      roomId: 0,
      roomName: null,
      toWho: null,
      message: { roomList: [] }, // 定义 message 并包含 roomList 属性
    };
  },
  // 在 computed 中添加 filteredMessages 计算属性
  computed: {
    ...mapGetters({
      id: "userId",
    }),
    showOnlineUsers() {
      return this.onlineUsers.length > 0;
    },
    // 消息过滤
    filteredMessages() {
      console.log("Current room title:", this.roomTitle);
      console.log("Current user ID:", this.userID);
      console.log("All messages:", this.messages);

      // 进行条件判断
      if (this.isGroup === "1") {
        // 群聊消息过滤
        const filtered = this.messages.filter(
          (message) =>
            message.to == this.roomTitle || message.from == this.roomTitle
        );
        console.log("Filtered group messages:", filtered);
        return filtered;
      } else {
        // 私聊消息过滤
        console.log("这是私人发送的messages", this.messages);
        console.log("这是roomTitle", this.roomTitle);
        console.log("这是userId", this.userID);

        const filtered = this.messages.filter(
          (message) =>
            (message.from == this.userID && message.to == this.toWho) ||
            (message.to == this.userID && message.from == this.toWho)
        );
        console.log("Filtered private messages:", filtered);
        return filtered;
      }
    },
  },

  methods: {
    async getUserID() {
      try {
        const response = await getInfo();
        this.userID = response.user.userId;
        return this.userID;
      } catch (error) {
        console.error("获取用户信息时出错:", error);
        throw error;
      }
    },
    //连接websocket用户展示
    async connectWebSocket() {
      const userID = await this.getUserID();
      this.ws = new WebSocket(
        "ws://127.0.0.1:8080/websocket/message/" + userID
      );

      this.ws.onopen = () => {
        console.log("WebSocket connected");
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        console.log("Received WebSocket message:", message);

        if (message.onlineUsers) {
          this.$set(
            this,
            "onlineUsers",
            message.onlineUsers.map((user) => ({
              ...user,
              unreadMessages: 0,
            }))
          );
          console.log("Updated online users:", this.onlineUsers);
        } else if (message.roomList) {
          this.$set(this.message, "roomList", message.roomList);
        } else {
          this.$set(this.messages, this.messages.length, {
            from: message.from,
            to: message.to,
            content: message.content,
          });

          console.log(
            "接收到消息：",
            message.content,
            "来自用户：",
            message.from,
            "发送给用户：",
            message.to
          );
          if (message.to === this.userID) {
            const userIndex = this.onlineUsers.findIndex(
              (user) => user.userId === message.from
            );
            if (userIndex !== -1) {
              this.$set(this.onlineUsers, userIndex, {
                ...this.onlineUsers[userIndex],
                unreadMessages: this.onlineUsers[userIndex].unreadMessages + 1,
              });
            }
          }
        }
      };

      this.ws.onclose = () => {
        console.log("WebSocket disconnected");
      };

      this.ws.onerror = (error) => {
        console.error("WebSocket error", error);
      };
    },
    sendMessage(Id) {
      if (this.inputMessage.trim() !== "") {
        // 直接获取最新的 isGroup 值
        const isGroup = this.isGroup;
        // 判断是否为群聊，如果是，则将接收方设置为 roomId，否则保持原样
        const to = Id;
        const message = {
          isGroup: isGroup,
          to: this.toWho,
          from: this.userID,
          content: this.inputMessage,
        };
        const string = JSON.stringify(message);
        this.ws.send(string);
        // 把消息推送到聊天框
        this.messages.push({
          isGroup: this.isGroup,
          from: this.userID,
          to: this.toWho,
          content: this.inputMessage, // 将 userId 改为 this.userID
        });
        console.log("发送消息：", this.inputMessage, ",给", Id);
        console.log("当前消息列表:", this.messages); // 打印消息列表
        this.inputMessage = ""; // 在这里清空输入框
      }
    },

    changeRoomTitle(name, type, user) {
      if (type === "user") {
        // 单聊
        this.isGroup = "0";
        this.toWho = user.userId;
        this.roomIcon = "el-icon-user-solid";
        this.roomTitle = user.username; // 确保设置为 userId
        console.log("xingming", this.toWho);
        const userIndex = this.onlineUsers.findIndex(
          (u) => u.userId === user.userId
        );
        if (userIndex !== -1) {
          this.$set(this.onlineUsers, userIndex, {
            ...user,
            unreadMessages: 0,
          });
        }
      } else if (type === "group") {
        // 群聊
        this.isGroup = "1";
        this.roomIcon = "el-icon-s-promotion";
        this.toWho = name;
        this.roomTitle = name; // 设置为 roomName
        console.log("群聊名称---", this.roomTitle);
      }
      console.log("Changed room title to:", this.roomTitle);
    },

    // 进入聊天室
    enterRoom(roomName) {
      // 图标
      this.roomIcon = "el-icon-s-promotion";
      // 将聊天消息发送内容标识为群聊
      this.isGroup = "1";
      // 向后端发送消息，告知用户加入了指定的聊天室
      const message = {
        joinGroup: roomName,
        userId: this.userID,
      };
      this.changeRoomTitle(roomName, "group", roomName);

      this.ws.send(JSON.stringify(message));

      console.log("进入聊天室：", roomName);
      console.log("的isGroupe", this.isGroup);
    },
  },
  watch: {
    "message.roomList"(newVal, oldVal) {
      console.log("Room list updated:", newVal);
    },
  },
  mounted() {
    this.connectWebSocket();
    console.log("Initial room list:", this.message.roomList);
    console.log("Initial messages:", this.messages);
    console.log("Room title:", this.roomTitle);
    console.log("当前的isGroupe", this.isGroup);
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
};
</script>

<style scoped>
.chat-room {
  max-width: 600px;
  margin: 50px auto;
}

.messages {
  height: 400px;
  /* 设置对话框容器的高度 */
  max-height: 50%;
  overflow-y: auto;
  margin-bottom: 20px;
}

.my-message {
  text-align: right;
}

.other-message {
  text-align: left;
}

.message-bubble {
  display: inline-block;
  background-color: #e0e0e0;
  padding: 5px 10px;
  border-radius: 10px;
  margin: 5px;
}

.unread-badge {
  background-color: red;
  color: white;
  padding: 3px 6px;
  border-radius: 50%;
  font-size: 12px;
  margin-left: 5px;
}

.message {
  margin: 5px 0;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-message {
  flex: 1;
  max-width: 90%;
}
</style>
